// pages/Pet/PetTravel/PetTravel.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetSpecies , queryPetStore , queryPetRravelGoods } from '../../../api/pet';
import { throttle , formatTime } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    showParams: false,
    queryLongitude: wx.getStorageSync('longitude'),
    queryLatitude: wx.getStorageSync('latitude'),
    storeId: '',
    storeList: [],
    page: 0,
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    petSpecList: [], // 宠物类型列表
    speciesId: '',
    popSpeciesId: '',
    startTime: '',
    selStartTime: '',
    endTime: '',
    selEndTime: '',
    showTime: false,
    timeActive: '0',
    minDate: new Date().getTime(),
    maxDate: new Date().getTime() + 30 * 24 * 3600 * 1000,
    currentDate: new Date().getTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this._queryPetSpecies();
    this._queryPetStore();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._queryPetRravelGoods()
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._queryPetRravelGoods()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  showPar(){
    this.setData({
      popSpeciesId: this.data.speciesId,
      showParams: true,
    })
    console.log(this.selectComponent('#popTabs'),'poptab')
    this.selectComponent('#popTabs').resize();
  },
  onClose(){
    this.setData({
      showParams: false,
    })
  },
  // 切换宠物种类
  onChange(e){
    console.log(e)
    console.log(this.data.speciesId,'specId')
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    this.setData({
      speciesId: e.detail.name,
    })
    if(type == 'main'){
      this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      this._queryPetRravelGoods();
    }
  },
  onPopChange(e){
    this.setData({
      popSpeciesId: e.detail.name
    })
  },
  // 获取宠物种类信息
  _queryPetSpecies(){
    let _this = this;
    queryPetSpecies({size: 99})
    .then(res => {
      if(res.success){
        var list = [{ id: '', name: '全部'}];
        list = list.concat(res.data.content);
        _this.setData({
          petSpecList: list,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
   // 获取宠物门店
   _queryPetStore() {
    let _this = this;
    const { queryLongitude, queryLatitude } = _this.data;
    queryPetStore({size: 99, queryLongitude: queryLongitude, queryLatitude: queryLatitude,})
      .then(res => {
        if (res.success) {
          _this.setData({
            // storeId: res.data.content.length > 0 ? res.data.content[0].id : '',
            storeList: res.data.content,
          })
          _this._queryPetRravelGoods();
        } else {
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  // 获取宠物旅游商品
  _queryPetRravelGoods(){
    let _this = this;
    const { storeId , speciesId , startTime , endTime } = _this.data;
    queryPetRravelGoods({speciesId: speciesId,storeId: storeId,activityStartTime: startTime,activityEndTime: endTime})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        if(_this.data.page == 0){
          list = res.data.content;
        }else{
          list = list.concat(res.data.content);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 切换门店
  selStore(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      storeId: item.id,
    })
  },
  // 重置筛选
  resEvent(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      speciesId: 0,
      showParams: false,
      storeId: '',
      // storeId: this.data.storeList.length > 0 ? this.data.storeList[0].id : '',
      startTime: '',
      endTime: '',
      selStartTime: '',
      selEndTime: '',
      dataList : [],
    })
    this.selectComponent('#tabs').resize();
    this._queryPetRravelGoods()
  },
  // 确认查询
  confirm(){
    let _this = this;
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      showParams: false,
      speciesId: _this.data.popSpeciesId,
      startTime: _this.data.selStartTime,
      endTime: _this.data.selEndTime,
      dataList : [],
    })
    this._queryPetRravelGoods()
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.setStorageSync('selNearByStore','0');
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 选择时间
  selTime(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      timeActive: item,
      showTime: true,
    })
  },
  timeConfirm(event){
    console.log(event,'event')
    console.log(formatTime(new Date(event.detail),'Y-M-D h:m:s'),'Y-M-D h:m:s');
    var date = formatTime(new Date(event.detail),'Y-M-D');
    this.setData({
      currentDate: event.detail,
      showTime: false,
    })
    if(this.data.timeActive == '0'){
      this.setData({
        selStartTime: date,
      })
    }else{
      this.setData({
        selEndTime: date,
      })
    }
  },
})